<script setup>
import { onMounted, reactive, ref, watch } from 'vue';

import { DictEnum } from '@vben/constants';

import {
  PieChartTwoTone,
  ProjectTwoTone,
  ShopTwoTone,
} from '@ant-design/icons-vue';
import dayjs from 'dayjs';
import * as echarts from 'echarts';

import {
  // 引入详情API
  queryCustomerActivity,
  queryDeptList,
  queryProductActivity,
  queryRefundAndReturnStats,
  querySaleNumOrMoney,
  selectPersonServerSort,
  selectPersonSort,
  selectProductSort,
} from '#/api/hm/home/index.ts';
import { productList } from '#/api/hm/product/index.ts';
import { deptList } from '#/api/system/dept';
import { renderDict } from '#/utils/render';

import PaymentDetailModal from './PaymentDetailModal.vue';

// --- 弹窗逻辑 (原生控制) ---
const isDetailModalVisible = ref(false);
const detailModalTitle = ref('');
const detailModalParams = ref({});

function handleOpenRepaymentDetails(title, params) {
  console.log('打开回款详情', title, params);
  detailModalTitle.value = `[${title}] 的回款详情`;
  detailModalParams.value = params;
  isDetailModalVisible.value = true;
}

// --- 1. 店铺销量排名 (Store Sales Ranking) ---
const storeSalesRankingColumns = [
  { title: '序号', dataIndex: 'index', width: 60, align: 'center' },
  { title: '店铺', dataIndex: 'name', key: 'name', align: 'center' },
  {
    title: '销售额',
    dataIndex: 'salesVolume',
    key: 'salesVolume',
    align: 'center',
  },
  {
    title: '回款额',
    dataIndex: 'repaymentAmount',
    key: 'repaymentAmount',
    align: 'center',
  },
];
const storeSalesRanking = ref([]);
const storeSalesDate = ref(dayjs());
const storeSalesDateMode = ref('year');

async function getSalesRankings() {
  if (!storeSalesDate.value) return;
  const formattedDate = storeSalesDate.value.format(
    storeSalesDateMode.value === 'year' ? 'YYYY' : 'YYYY-MM',
  );
  const params = { size: 999, date: formattedDate };
  try {
    const data = await queryDeptList(params);
    // 在映射数据时，确保包含了用于查询详情的唯一ID
    storeSalesRanking.value = data.rows.map((item) => ({
      id: item.saleDept,
      name: item.saleDeptName,
      salesVolume: item.saleAmount,
      repaymentAmount: item.returnAmount,
    }));
  } catch (error) {
    console.error('Error fetching store sales rankings:', error);
    storeSalesRanking.value = [];
  }
}

function onStoreSalesFilterChange() {
  getSalesRankings();
}

// --- 2. 个人销量排名 (Personal Sales Ranking) ---
const columns3 = [
  { title: '序号', dataIndex: 'index', width: 60, align: 'center' },
  { title: '人员', dataIndex: 'name', key: 'name', align: 'center' },
  {
    title: '销售额',
    dataIndex: 'salesVolume',
    key: 'salesVolume',
    align: 'center',
  },
  {
    title: '回款额',
    dataIndex: 'repaymentAmount',
    key: 'repaymentAmount',
    align: 'center',
  },
];
const personSalesDate = ref(dayjs());
const personSalesDateMode = ref('year');
const dataSource3 = ref([]);

async function getSalesRankingByPerson() {
  if (!personSalesDate.value) return;
  const formattedDate = personSalesDate.value.format(
    personSalesDateMode.value === 'year' ? 'YYYY' : 'YYYY-MM',
  );
  const params = { size: 999, date: formattedDate };
  try {
    const data = await selectPersonSort(params);
    // 包含唯一ID (saleUserId)
    dataSource3.value = data.rows.map((item) => ({
      id: item.saleUser,
      name: item.saleUserName,
      salesVolume: (item.saleAmount / 10).toFixed(2),
      repaymentAmount: (item.returnAmount / 10).toFixed(2),
    }));
  } catch (error) {
    console.error('Error fetching person sales rankings:', error);
    dataSource3.value = [];
  }
}

function onSalesRankingByPersonChange() {
  getSalesRankingByPerson();
}

// --- 3. 个人服务人员数量排名 (Personal Service Count Ranking) ---
const columns4 = [
  { title: '序号', dataIndex: 'index', width: 60, align: 'center' },
  { title: '人员', dataIndex: 'name', key: 'name', align: 'center' },
  { title: '客户数量', dataIndex: 'num', key: 'num', align: 'center' },
  {
    title: '服务次数',
    dataIndex: 'frequency',
    key: 'frequency',
    align: 'center',
  },
];
const dataSource4 = ref([]);
const personServiceDate = ref(dayjs());
const personServiceDateMode = ref('year');

async function selectPersonServerSortFunction() {
  if (!personServiceDate.value) return;
  const formattedDate = personServiceDate.value.format(
    personServiceDateMode.value === 'year' ? 'YYYY' : 'YYYY-MM',
  );
  const params = { size: 999, date: formattedDate };
  try {
    const data = await selectPersonServerSort(params);
    dataSource4.value = data.rows.map((item) => ({
      name: item.saleUserName,
      num: item.saleNumTotal,
      frequency: item.saleNum,
    }));
  } catch (error) {
    console.error('Error fetching personal service rankings:', error);
    dataSource4.value = [];
  }
}

function onPersonServiceFilterChange() {
  selectPersonServerSortFunction();
}

// --- 4. 主产品单品各店销售排名 (Main Product Sales Ranking by Store) ---
const dataSource2 = ref([]);
const columns2 = [
  { title: '序号', dataIndex: 'index', width: 60, align: 'center' },
  { title: '店铺', dataIndex: 'name', key: 'name', align: 'center' },
  {
    title: '主产品',
    dataIndex: 'mainProduct',
    key: 'mainProduct',
    align: 'center',
  },
  {
    title: '回款额',
    dataIndex: 'repaymentAmount',
    key: 'repaymentAmount',
    align: 'center',
  },
];
const productRankDate = ref(dayjs());
const productRankDateMode = ref('year');
const productRankProductId = ref('');

async function selectProductSortFunction() {
  if (!productRankProductId.value || !productRankDate.value) {
    dataSource2.value = [];
    return;
  }
  const formattedDate = productRankDate.value.format(
    productRankDateMode.value === 'year' ? 'YYYY' : 'YYYY-MM',
  );
  const params = {
    size: 999,
    date: formattedDate,
    productId: productRankProductId.value,
  };
  try {
    const data = await selectProductSort(params);
    // 包含唯一ID (saleDeptId)
    dataSource2.value = data.rows.map((item) => ({
      id: item.saleDept,
      name: item.saleDeptName,
      mainProduct: item.saleProductName,
      repaymentAmount: (item.returnAmount / 10).toFixed(2),
    }));
  } catch (error) {
    console.error('Error fetching main product sales ranking:', error);
    dataSource2.value = [];
  }
}

function onProductRankFilterChange() {
  selectProductSortFunction();
}

// --- ECharts Section (销售金额 & 产品销售) ---
const xsje = ref(null);
const myChart = ref(null);
const option = ref({});

const cpxs = ref(null);
const myChart1 = ref(null);
const option1 = ref({});

const salesAmountChartDate = ref(dayjs());
const salesAmountChartDateMode = ref('month');

const querySaleNumOrMoneyParams = ref({
  type: 'num',
  date: salesAmountChartDate.value.format(
    salesAmountChartDateMode.value === 'month' ? 'YYYY-MM' : 'YYYY',
  ),
});

async function getEchartsData() {
  try {
    const data = await querySaleNumOrMoney(querySaleNumOrMoneyParams.value);
    salesAmount(data);
    productSales(data);
  } catch (error) {
    console.error('Error fetching ECharts data:', error);
    if (myChart.value) myChart.value.clear();
    if (myChart1.value) myChart1.value.clear();
  }
}

function onSalesAmountChartFilterChange() {
  if (!salesAmountChartDate.value) return;
  querySaleNumOrMoneyParams.value.date = salesAmountChartDate.value.format(
    salesAmountChartDateMode.value === 'year' ? 'YYYY' : 'YYYY-MM',
  );
  getEchartsData();
}

watch(
  () => querySaleNumOrMoneyParams.value.type,
  () => {
    getEchartsData();
  },
);

function salesAmount(data) {
  if (!xsje.value) return;
  const dataMap = {
    已回款: {
      value: data?.returnSaleAmount
        ? (data.returnSaleAmount / 10).toFixed(2)
        : '0.00',
    },
    未回款: {
      value: data?.noReturnSaleAmount
        ? (data.noReturnSaleAmount / 10).toFixed(2)
        : '0.00',
    },
  };

  if (myChart.value) {
    myChart.value.dispose();
  }
  myChart.value = echarts.init(xsje.value);
  option.value = {
    title: [
      {
        text: data?.totalSaleAmount
          ? (data.totalSaleAmount / 10).toFixed(2)
          : '0.00',
        top: '48%',
        left: '35%',
        padding: [15, 0, 0, -20],
        textStyle: { color: '#080404', fontSize: 20, fontWeight: 'bold' },
      },
      {
        text: '销售金额',
        top: '48%',
        left: '35%',
        padding: [-15, 0, 0, -15],
        textStyle: { color: '#080404', fontSize: 18, fontWeight: '400' },
      },
    ],
    tooltip: { show: false, trigger: 'item' },
    legend: {
      textStyle: { fontSize: 14 },
      orient: 'vertical',
      right: '2%',
      top: 'middle',
      icon: 'circle',
      itemGap: 10,
      formatter: (name) => `${name}  |  ${dataMap[name]?.value || '0.00'}`,
    },
    series: [
      {
        type: 'pie',
        radius: ['45%', '55%'],
        center: ['38%', '50%'],
        itemStyle: {
          borderRadius: 5,
          borderColor: 'rgba(0,0,0,0)',
          borderWidth: 5,
        },
        label: { show: false },
        data: [
          {
            value: data?.returnSaleAmount
              ? (data.returnSaleAmount / 10).toFixed(2)
              : 0,
            name: '已回款',
            itemStyle: { color: '#17A790' },
          },
          {
            value: data?.noReturnSaleAmount
              ? (data.noReturnSaleAmount / 10).toFixed(2)
              : 0,
            name: '未回款',
            itemStyle: { color: '#FFD027' },
          },
        ],
      },
    ],
  };
  option.value && myChart.value.setOption(option.value);
  window.addEventListener('resize', () => myChart.value?.resize());
}

function productSales(data) {
  if (!cpxs.value) return;
  const saleNumbers = data.list?.map((item) =>
    querySaleNumOrMoneyParams.value.type === 'money'
      ? item.saleAmount / 10
      : item.saleNum,
  ) || [0];
  const maxValue = Math.max(0, ...saleNumbers.map((val) => Number(val) || 0));
  const dynamicMax =
    maxValue > 0
      ? Math.ceil(maxValue * 1.2)
      : (querySaleNumOrMoneyParams.value.type === 'money'
        ? 500
        : 50);
  const dynamicInterval =
    Math.ceil(
      dynamicMax /
        5 /
        (querySaleNumOrMoneyParams.value.type === 'money' ? 100 : 1),
    ) * (querySaleNumOrMoneyParams.value.type === 'money' ? 100 : 1);

  if (myChart1.value) {
    myChart1.value.dispose();
  }
  myChart1.value = echarts.init(cpxs.value);
  option1.value = {
    grid: {
      top: '20%',
      left: '1%',
      right: '1%',
      bottom: '20%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      axisLine: { lineStyle: { color: 'skyblue', width: '1' } },
      axisTick: { show: true },
      axisLabel: {
        show: true,
        color: '#666',
        fontSize: data.list?.length > 5 ? 10 : 14,
        rotate: data.list?.length > 5 ? 45 : 0,
        interval: 0,
        width: data.list?.length > 5 ? 60 : undefined,
        overflow: 'truncate',
        ellipsis: '...',
        align: 'center',
      },
      data: data.list?.map((item) => item.saleProductName) || [],
    },
    yAxis: {
      show: true,
      name:
        querySaleNumOrMoneyParams.value.type === 'money'
          ? '金额 (x10元)'
          : '数量',
      nameTextStyle: { color: '#666', fontSize: 14 },
      min: 0,
      max: dynamicMax,
      interval: dynamicInterval > 0 ? dynamicInterval : undefined,
      splitLine: { show: true },
      axisLabel: { show: true, color: '#666', fontSize: '14' },
      axisLine: { lineStyle: { color: 'skyblue', width: '1' } },
      axisTick: { show: true },
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      backgroundColor: 'rgba(50,50,50,0.7)',
      textStyle: { color: '#fff', fontSize: 14 },
      extraCssText: 'box-shadow: 0 0 10px rgba(0,0,0,0.3);',
      formatter: (params) => {
        const axisValue = params[0].axisValue;
        const value = params[0].value;
        const seriesName =
          querySaleNumOrMoneyParams.value.type === 'money'
            ? '销售金额'
            : '销售数量';
        return `产品：${axisValue}<br/>${seriesName}：${value}`;
      },
    },
    series: [
      {
        name:
          querySaleNumOrMoneyParams.value.type === 'money'
            ? '销售金额'
            : '销售数量',
        type: 'bar',
        barWidth: 20,
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            x2: 0,
            y: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: '#29CEFF' },
              { offset: 1, color: '#25D2F1' },
            ],
          },
        },
        data:
          data.list?.map((item) => ({
            value:
              querySaleNumOrMoneyParams.value.type === 'money'
                ? (item.saleAmount / 10).toFixed(2)
                : item.saleNum,
            name: item.saleProductName,
          })) || [],
        label: {
          show: true,
          position: 'top',
          color: '#333',
          fontSize: 12,
          formatter: '{c}',
        },
      },
    ],
  };
  option1.value && myChart1.value.setOption(option1.value);
  window.addEventListener('resize', () => myChart1.value?.resize());
}

// --- Top Left Customer Stats ---
const customerNumRef = reactive({
  customerNum: 0,
  inServiceNum: 0,
  stopNum: 0,
  activeNum: 0,
  sleepNum: 0,
});
async function getCustomerNum() {
  try {
    const data = await queryCustomerActivity();
    customerNumRef.customerNum = data.total;
    customerNumRef.inServiceNum = data.num1;
    customerNumRef.stopNum = data.num2;
    customerNumRef.activeNum = data.num3;
    customerNumRef.sleepNum = data.num4;
  } catch (error) {
    console.error('Error fetching customer numbers:', error);
  }
}

// --- Top Right Product Stats ---
const productOptions = ref([]);
const productId = ref('');
const productStock = ref({ stockNum: 0, shopNum: 0, monthPickNum: 0 });

async function loadProductOptions() {
  try {
    const ret = await productList({
      pageNum: 1,
      pageSize: 999,
      status: '0',
      productType: 'CP',
    });
    const transOptions = ret.rows.map((item) => ({
      label: item.productName,
      value: item.productId.toString(),
    }));
    productOptions.value = transOptions;

    if (productOptions.value.length > 0) {
      if (!productId.value) {
        productId.value = productOptions.value[0].value;
      }
      if (!productRankProductId.value) {
        productRankProductId.value = productOptions.value[0].value;
      }
    }
  } catch (error) {
    console.error('Error fetching product list:', error);
    productOptions.value = [];
  }
}

async function productChange() {
  if (!productId.value) return;
  const params = { ProductId: productId.value };
  try {
    const data = await queryProductActivity(params);
    productStock.value.stockNum = data.stockNum;
    productStock.value.monthPickNum = data.pickNum;
    productStock.value.shopNum = data.shopNum;
  } catch (error) {
    console.error('Error fetching product activity:', error);
  }
}

// --- 新增：退款退货统计 ---
const refundChartRef = ref(null);
let refundChart = null;
const refundStore = ref('all');
const refundDate = ref(dayjs());
const refundDateMode = ref('year');
const storeOptions = ref([]);
const refundDetailsLoading = ref(false);
const refundDetailsData = ref([]);
const refundDetailColumns = [
  { title: '订单号', dataIndex: 'saleId', key: 'saleId', width: 180 }, // 对应后端 saleId
  {
    title: '退货名称',
    dataIndex: 'saleProductName',
    key: 'saleProductName',
    width: 100,
  },
  {
    title: '退款金额',
    dataIndex: 'refundAmount',
    key: 'refundAmount',
    width: 120,
    customRender: ({ text }) => `¥ ${Number.parseFloat(text || 0).toFixed(2)}`,
  }, // 格式化金额
  { title: '退货数量', dataIndex: 'returnNum', key: 'returnNum', width: 100 },
  { title: '退货时间', dataIndex: 'applyTime', key: 'applyTime', width: 150 }, // 对应后端 applyTime
  {
    title: '退货原因',
    dataIndex: 'reasonCode',
    key: 'reasonCode',
    customRender: ({ text }) => {
      if (text) {
        // 单元格内容翻译
        return renderDict(text, DictEnum.RETURN_REASON);
      }
      return '-';
    },
  }, // 对应后端 reasonCode
  { title: '备注', dataIndex: 'description', key: 'description' }, // 对应后端 reasonCode
];
// **新增：分页状态变量**
const refundDetailsCurrentPage = ref(1);
const refundDetailsPageSize = ref(5);
const refundDetailsTotal = ref(0);

// **新增：总计数量显示变量**
const totalRefundAmountDisplay = ref('0.00');
const totalReturnNumDisplay = ref('0');

// **新增：按销售人员统计的数据和列**
const salespersonRefundStatsData = ref([]);

// **新增：当前选中的销售人员ID，用于过滤明细表格**
const selectedSalespersonId = ref(null);

const salespersonStatsColumns = [
  { title: '序号', dataIndex: 'index', width: 60, align: 'center' },
  {
    title: '销售员',
    dataIndex: 'salespersonName',
    key: 'salespersonName',
    width: 100,
  },
  {
    title: '退款金额',
    dataIndex: 'refundAmount',
    key: 'refundAmount',
    width: 120,
    customRender: ({ text }) => `¥ ${Number.parseFloat(text || 0).toFixed(2)}`,
  },
  {
    title: '退货数量',
    dataIndex: 'returnedTotal',
    key: 'returnedTotal',
    width: 100,
  }, // 已提货+未提货总和
];

// **新增：点击销售人员统计表格的退款金额**
function handleSalespersonClick(salespersonId) {
  if (selectedSalespersonId.value === salespersonId) {
    // 再次点击同一个销售人员，取消过滤
    selectedSalespersonId.value = null;
  } else {
    // 点击新的销售人员，设置过滤
    selectedSalespersonId.value = salespersonId;
  }
  // 重新加载明细数据，并重置页码到第一页
  refundDetailsCurrentPage.value = 1;
  updateRefundStats();
}

// **新增：处理表格分页变化**
function onRefundDetailsTableChange(pagination) {
  refundDetailsCurrentPage.value = pagination.current;
  refundDetailsPageSize.value = pagination.pageSize;
  updateRefundStats(); // 重新加载数据
}

// 统一更新退款统计模块（图表和表格）
async function updateRefundStats() {
  refundDetailsLoading.value = true;
  if (!refundDate.value) {
    refundDetailsLoading.value = false;
    return;
  }
  const formattedDate = refundDate.value.format(
    refundDateMode.value === 'year' ? 'YYYY' : 'YYYY-MM',
  );
  const params = {
    storeId: refundStore.value,
    date: formattedDate,
    dateMode: refundDateMode.value,
    pageNum: refundDetailsCurrentPage.value,
    pageSize: refundDetailsPageSize.value,
    salespersonId: selectedSalespersonId.value, // 如果为null，后端应处理为不进行过滤
  };
  try {
    const response = await queryRefundAndReturnStats(params); // 调用后端接口
    const data = response.chartData; // 图表数据
    const details = response.detailsData.rows; // 明细数据

    // 更新图表
    if (!refundChartRef.value) return; // 确保DOM元素已加载
    if (refundChart) {
      refundChart.dispose();
    }
    refundChart = echarts.init(refundChartRef.value);
    const option = {
      tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
      legend: {
        data: ['退款金额', '退货数量(产品)', '退货数量(赠品)'],
        bottom: 0,
      },
      grid: { left: '3%', right: '4%', bottom: '10%', containLabel: true },
      xAxis: [{ type: 'category', data: data.labels }],
      yAxis: [
        {
          type: 'value',
          name: '金额 (元)',
          axisLabel: { formatter: '¥ {value}' },
        },
        {
          type: 'value',
          name: '数量',
          position: 'right',
          axisLabel: { formatter: '{value} 件' },
        },
      ],
      series: [
        {
          name: '退款金额',
          type: 'bar',
          data: data.refundAmount,
          itemStyle: { color: '#5470C6' },
        },
        {
          name: '退货数量(产品)',
          type: 'bar',
          yAxisIndex: 1,
          data: data.returnedPickedCP,
          itemStyle: { color: '#91CC75' },
        },
        {
          name: '退货数量(赠品)',
          type: 'bar',
          yAxisIndex: 1,
          data: data.returnedPickedZP,
          itemStyle: { color: '#EE6666' },
        },
      ],
    };
    refundChart.setOption(option);
    window.addEventListener('resize', () => refundChart?.resize());

    // 更新表格
    refundDetailsData.value = details;
    // **新增：更新表格总数**
    refundDetailsTotal.value = response.detailsData.total;

    // **新增：计算并显示总计数量**
    const totalRefund = data.refundAmount.reduce(
      (sum, val) => sum + Number.parseFloat(val || 0),
      0,
    );
    const totalPicked = data.returnedPickedCP.reduce(
      (sum, val) => sum + Number.parseFloat(val || 0),
      0,
    );
    const totalUnpicked = data.returnedPickedZP.reduce(
      (sum, val) => sum + Number.parseFloat(val || 0),
      0,
    );

    totalRefundAmountDisplay.value = totalRefund.toFixed(2);
    totalReturnNumDisplay.value = (totalPicked + totalUnpicked).toFixed(0);

    // **新增：更新销售人员统计表格数据**
    if (response.chartData.salespersonStats) {
      salespersonRefundStatsData.value =
        response.chartData.salespersonStats.map((item, index) => ({
          index: index + 1,
          salespersonId: item.salespersonId,
          salespersonName: item.salespersonName,
          refundAmount: item.refundAmount
            ? Number.parseFloat(item.refundAmount).toFixed(2)
            : '0.00',
          returnedTotal: item.returnedPickedCP + item.returnedPickedZP, // 总退货数量
        }));
    } else {
      salespersonRefundStatsData.value = [];
    }
  } catch (error) {
    console.error('Error fetching refund and return stats:', error);
    if (refundChart) refundChart.clear();
    refundDetailsData.value = [];
    refundDetailsTotal.value = 0;
    totalRefundAmountDisplay.value = '0.00';
    totalReturnNumDisplay.value = '0';
    salespersonRefundStatsData.value = []; // 清空人员统计数据
  } finally {
    refundDetailsLoading.value = false;
  }
}

function onRefundFilterChange() {
  // **新增：筛选条件变化时，重置页码到第一页**
  refundDetailsCurrentPage.value = 1;
  // **新增：重置销售人员过滤**
  selectedSalespersonId.value = null;
  updateRefundStats();
}

// 加载店铺选项
async function loadStoreOptions() {
  try {
    const ret = await deptList({ deptCategory: 'DP' }); // 获取所有店铺
    const options = ret.map((item) => ({
      label: item.deptName,
      value: item.deptId.toString(),
    }));
    storeOptions.value = [{ label: '全部店铺', value: 'all' }, ...options];
  } catch (error) {
    console.error('Error loading store options:', error);
  }
}

// --- onMounted ---
onMounted(async () => {
  await loadProductOptions();
  await loadStoreOptions();
  if (productId.value) {
    await productChange();
  }
  querySaleNumOrMoneyParams.value.date = salesAmountChartDate.value.format(
    salesAmountChartDateMode.value === 'month' ? 'YYYY-MM' : 'YYYY',
  );
  getEchartsData();
  getCustomerNum();
  getSalesRankings();
  getSalesRankingByPerson();
  selectPersonServerSortFunction();
  if (productRankProductId.value) {
    selectProductSortFunction();
  }
  // 初始化新增的模块
  updateRefundStats();
});
</script>

<template>
  <div class="p-4">
    <!-- 顶部和中部的HTML结构保持不变 -->
    <div class="flex">
      <div class="wd-33">
        <a-card style="height: 100%">
          <div class="h-120 flex-center p-4">
            <div class="ml-4">
              <div class="text-28-main-700">
                {{ customerNumRef.customerNum }}
              </div>
              <div class="text-14-sub-400 mt-4">客户总数</div>
            </div>
            <div>
              <a-divider
                type="vertical"
                style="height: 80px; margin-left: 12px; background-color: #999"
              />
            </div>
            <div class="ml-4">
              <div>
                <span class="text-14-tip-500">在服</span><span class="text-14-sub-400 ml-2">{{
                  customerNumRef.inServiceNum
                }}</span>
              </div>
              <div class="mt-8">
                <span class="text-14-tip-500">停用</span><span class="text-14-sub-400 ml-2">{{
                  customerNumRef.stopNum
                }}</span>
              </div>
            </div>
            <div class="ml-8">
              <div>
                <span class="text-14-tip-500">活跃</span><span class="text-14-sub-400 ml-2">{{
                  customerNumRef.activeNum
                }}</span>
              </div>
              <div class="mt-8">
                <span class="text-14-tip-500">休眠</span><span class="text-14-sub-400 ml-2">{{
                  customerNumRef.sleepNum
                }}</span>
              </div>
            </div>
          </div>
        </a-card>
      </div>
      <div class="wd-66 ml-4">
        <a-card>
          <template #extra>
            <ASelect
              v-model:value="productId"
              :options="productOptions"
              placeholder="请选择产品"
              style="width: 150px"
              :show-search="true"
              option-filter-prop="label"
              @change="productChange"
              :allow-clear="false"
            />
          </template>
          <div class="h-120 flex-center">
            <div class="wd-33 flex-center">
              <div><ShopTwoTone :style="{ fontSize: '32px' }" /></div>
              <div class="ml-4">
                <div class="text-28-main-700">{{ productStock.shopNum }}</div>
                <div class="text-14-tip-500">店铺数量</div>
              </div>
            </div>
            <a-divider
              type="vertical"
              style="height: 80px; background-color: #999"
            />
            <div class="wd-33 flex-center">
              <div><ProjectTwoTone :style="{ fontSize: '32px' }" /></div>
              <div class="ml-4">
                <div class="text-28-main-700">{{ productStock.stockNum }}</div>
                <div class="text-14-tip-500">各主产品的库存数量</div>
              </div>
            </div>
            <a-divider
              type="vertical"
              style="height: 80px; background-color: #999"
            />
            <div class="wd-33 flex-center">
              <div><PieChartTwoTone :style="{ fontSize: '32px' }" /></div>
              <div class="ml-4">
                <div class="text-28-main-700">
                  {{ productStock.monthPickNum }}
                </div>
                <div class="text-14-tip-500">各主产品当月提货数量</div>
              </div>
            </div>
          </div>
        </a-card>
      </div>
    </div>

    <div class="mt-4 flex">
      <div class="wd-33">
        <a-card>
          <div class="flex">
            <div class="line-blue"></div>
            <div class="text-18-sub-600 ml-2 flex-1">销售金额</div>
            <div
              class="flex-end"
              style="display: flex; gap: 8px; align-items: center"
            >
              <a-radio-group
                v-model:value="salesAmountChartDateMode"
                @change="onSalesAmountChartFilterChange"
                size="small"
              >
                <a-radio-button value="year">年</a-radio-button>
                <a-radio-button value="month">月</a-radio-button>
              </a-radio-group>
              <a-date-picker
                v-model:value="salesAmountChartDate"
                :picker="salesAmountChartDateMode"
                @change="onSalesAmountChartFilterChange"
                size="small"
                :allow-clear="false"
                style="width: 120px"
              />
            </div>
          </div>
          <div ref="xsje" style="height: 400px"></div>
        </a-card>
      </div>
      <div class="wd-66 ml-4">
        <a-card>
          <div class="flex">
            <div class="line-blue"></div>
            <div class="text-18-sub-600 ml-2 flex-1">产品销售</div>
            <div class="flex-end">
              <a-radio-group
                v-model:value="querySaleNumOrMoneyParams.type"
                button-style="solid"
                size="small"
                @change="getEchartsData"
              >
                <a-radio-button value="num">销售数量</a-radio-button>
                <a-radio-button value="money">销售金额</a-radio-button>
              </a-radio-group>
            </div>
          </div>
          <div ref="cpxs" style="height: 400px"></div>
        </a-card>
      </div>
    </div>

    <a-row class="mt-4">
      <a-col :span="24">
        <a-card>
          <div class="flex">
            <div class="line-blue"></div>
            <div class="text-18-sub-600 ml-2">销量排名</div>
          </div>
          <div class="flex-between mt-4">
            <!-- 店铺销量排名卡片 -->
            <div class="card p-4">
              <div class="text-16-tip">店铺销量排名</div>
              <div class="filter-controls">
                <a-radio-group
                  v-model:value="storeSalesDateMode"
                  @change="onStoreSalesFilterChange"
                  size="small"
                >
                  <a-radio-button value="year">年</a-radio-button>
                  <a-radio-button value="month">月</a-radio-button>
                </a-radio-group>
                <a-date-picker
                  v-model:value="storeSalesDate"
                  :picker="storeSalesDateMode"
                  @change="onStoreSalesFilterChange"
                  size="small"
                  :allow-clear="false"
                  style="width: 120px"
                />
              </div>
              <div class="mt-4">
                <a-table
                  :data-source="storeSalesRanking"
                  :columns="storeSalesRankingColumns"
                  :pagination="false"
                  size="small"
                >
                  <template #bodyCell="{ column, record, index }">
                    <template v-if="column.dataIndex === 'index'">
                      <img
                        v-if="index === 0"
                        src="./j.png"
                        alt="金牌"
                        style="width: 20px; height: 20px"
                      />
                      <img
                        v-else-if="index === 1"
                        src="./y.png"
                        alt="银牌"
                        style="width: 20px; height: 20px"
                      />
                      <img
                        v-else-if="index === 2"
                        src="./t.png"
                        alt="铜牌"
                        style="width: 20px; height: 20px"
                      />
                      <span v-else>{{ index + 1 }}</span>
                    </template>
                    <template v-if="column.key === 'salesVolume'">
                      {{
                        record.salesVolume
                          ? (parseFloat(record.salesVolume) / 10).toFixed(2)
                          : '0.00'
                      }}
                    </template>
                    <!-- 回款额列，添加点击功能 -->
                    <template v-if="column.key === 'repaymentAmount'">
                      <a-button
                        type="link"
                        @click="
                          handleOpenRepaymentDetails(record.name, {
                            type: 'store',
                            id: record.id,
                            date: storeSalesDate.format(
                              storeSalesDateMode === 'year'
                                ? 'YYYY'
                                : 'YYYY-MM',
                            ),
                          })
                        "
                        style="height: auto; padding: 0"
                      >
                        {{
                          record.repaymentAmount
                            ? (parseFloat(record.repaymentAmount) / 10).toFixed(
                                2,
                              )
                            : '0.00'
                        }}
                      </a-button>
                    </template>
                  </template>
                </a-table>
              </div>
            </div>

            <!-- 主产品单品各店销售排名卡片 -->
            <div class="card ml-4 p-4">
              <div class="text-16-tip">主产品单品各店销售排名</div>
              <div class="filter-controls-vertical">
                <div style="display: flex; gap: 8px; align-items: center">
                  <a-radio-group
                    v-model:value="productRankDateMode"
                    @change="onProductRankFilterChange"
                    size="small"
                  >
                    <a-radio-button value="year">年</a-radio-button>
                    <a-radio-button value="month">月</a-radio-button>
                  </a-radio-group>
                  <a-date-picker
                    v-model:value="productRankDate"
                    :picker="productRankDateMode"
                    @change="onProductRankFilterChange"
                    size="small"
                    :allow-clear="false"
                    style="width: 120px"
                  />
                </div>
                <ASelect
                  v-model:value="productRankProductId"
                  :options="productOptions"
                  placeholder="请选择产品"
                  style="width: 100%"
                  :show-search="true"
                  option-filter-prop="label"
                  @change="onProductRankFilterChange"
                  size="small"
                  :allow-clear="false"
                />
              </div>
              <div class="mt-4">
                <a-table
                  :data-source="dataSource2"
                  :columns="columns2"
                  :pagination="false"
                  size="small"
                >
                  <template #bodyCell="{ column, record, index }">
                    <template v-if="column.dataIndex === 'index'">
                      <img
                        v-if="index === 0"
                        src="./j.png"
                        alt="金牌"
                        style="width: 20px; height: 20px"
                      />
                      <img
                        v-else-if="index === 1"
                        src="./y.png"
                        alt="银牌"
                        style="width: 20px; height: 20px"
                      />
                      <img
                        v-else-if="index === 2"
                        src="./t.png"
                        alt="铜牌"
                        style="width: 20px; height: 20px"
                      />
                      <span v-else>{{ index + 1 }}</span>
                    </template>
                    <!-- 回款额列，添加点击功能 (注意：原dataIndex为salesVolume，这里改为repaymentAmount) -->
                    <template v-if="column.key === 'repaymentAmount'">
                      <a-button
                        type="link"
                        @click="
                          handleOpenRepaymentDetails(record.name, {
                            type: 'product_store',
                            id: record.id,
                            date: productRankDate.format(
                              productRankDateMode === 'year'
                                ? 'YYYY'
                                : 'YYYY-MM',
                            ),
                            productId: productRankProductId,
                          })
                        "
                        style="height: auto; padding: 0"
                      >
                        {{ record.repaymentAmount }}
                      </a-button>
                    </template>
                  </template>
                </a-table>
              </div>
            </div>

            <!-- 个人销量排名卡片 -->
            <div class="card ml-4 p-4">
              <div class="text-16-tip">个人销量排名</div>
              <div class="filter-controls-vertical">
                <div style="display: flex; gap: 8px; align-items: center">
                  <a-radio-group
                    v-model:value="personSalesDateMode"
                    @change="onSalesRankingByPersonChange"
                    size="small"
                  >
                    <a-radio-button value="year">年</a-radio-button>
                    <a-radio-button value="month">月</a-radio-button>
                  </a-radio-group>
                  <a-date-picker
                    v-model:value="personSalesDate"
                    :picker="personSalesDateMode"
                    @change="onSalesRankingByPersonChange"
                    size="small"
                    :allow-clear="false"
                    style="width: 120px"
                  />
                </div>
              </div>
              <div class="mt-4">
                <a-table
                  :data-source="dataSource3"
                  :columns="columns3"
                  :pagination="false"
                  size="small"
                >
                  <template #bodyCell="{ column, record, index }">
                    <template v-if="column.dataIndex === 'index'">
                      <img
                        v-if="index === 0"
                        src="./j.png"
                        alt="金牌"
                        style="width: 20px; height: 20px"
                      />
                      <img
                        v-else-if="index === 1"
                        src="./y.png"
                        alt="银牌"
                        style="width: 20px; height: 20px"
                      />
                      <img
                        v-else-if="index === 2"
                        src="./t.png"
                        alt="铜牌"
                        style="width: 20px; height: 20px"
                      />
                      <span v-else>{{ index + 1 }}</span>
                    </template>
                    <!-- 回款额列，添加点击功能 -->
                    <template v-if="column.key === 'repaymentAmount'">
                      <a-button
                        type="link"
                        @click="
                          handleOpenRepaymentDetails(record.name, {
                            type: 'person',
                            id: record.id,
                            date: personSalesDate.format(
                              personSalesDateMode === 'year'
                                ? 'YYYY'
                                : 'YYYY-MM',
                            ),
                          })
                        "
                        style="height: auto; padding: 0"
                      >
                        {{ record.repaymentAmount }}
                      </a-button>
                    </template>
                  </template>
                </a-table>
              </div>
            </div>

            <!-- 个人服务客户数量排名卡片 -->
            <div class="card ml-4 p-4">
              <div class="text-16-tip">个人服务客户数量排名</div>
              <div class="filter-controls-vertical">
                <div style="display: flex; gap: 8px; align-items: center">
                  <a-radio-group
                    v-model:value="personServiceDateMode"
                    @change="onPersonServiceFilterChange"
                    size="small"
                  >
                    <a-radio-button value="year">年</a-radio-button>
                    <a-radio-button value="month">月</a-radio-button>
                  </a-radio-group>
                  <a-date-picker
                    v-model:value="personServiceDate"
                    :picker="personServiceDateMode"
                    @change="onPersonServiceFilterChange"
                    size="small"
                    :allow-clear="false"
                    style="width: 120px"
                  />
                </div>
              </div>
              <div class="mt-4">
                <a-table
                  :data-source="dataSource4"
                  :columns="columns4"
                  :pagination="false"
                  size="small"
                >
                  <template #bodyCell="{ column, index }">
                    <template v-if="column.dataIndex === 'index'">
                      <img
                        v-if="index === 0"
                        src="./j.png"
                        alt="金牌"
                        style="width: 20px; height: 20px"
                      />
                      <img
                        v-else-if="index === 1"
                        src="./y.png"
                        alt="银牌"
                        style="width: 20px; height: 20px"
                      />
                      <img
                        v-else-if="index === 2"
                        src="./t.png"
                        alt="铜牌"
                        style="width: 20px; height: 20px"
                      />
                      <span v-else>{{ index + 1 }}</span>
                    </template>
                  </template>
                </a-table>
              </div>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 新增：退款退货统计 -->
    <a-row class="mt-4">
      <a-col :span="24">
        <a-card>
          <div class="flex">
            <div class="line-blue"></div>
            <div class="text-18-sub-600 ml-2 flex-1">退款退货统计</div>
            <div
              class="flex-end"
              style="display: flex; gap: 8px; align-items: center"
            >
              <a-select
                v-model:value="refundStore"
                :options="storeOptions"
                style="width: 150px"
                @change="onRefundFilterChange"
                size="small"
              />
              <a-radio-group
                v-model:value="refundDateMode"
                @change="onRefundFilterChange"
                size="small"
              >
                <a-radio-button value="year">年</a-radio-button>
                <a-radio-button value="month">月</a-radio-button>
              </a-radio-group>
              <a-date-picker
                v-model:value="refundDate"
                :picker="refundDateMode"
                @change="onRefundFilterChange"
                size="small"
                :allow-clear="false"
                style="width: 120px"
              />
            </div>
          </div>
          <div ref="refundChartRef" style="height: 400px"></div>

          <!-- **新增：按销售人员统计的退款退货表格** -->
          <template v-if="refundStore !== 'all'">
            <a-divider>销售人员退款退货统计</a-divider>
            <a-table
              :columns="salespersonStatsColumns"
              :data-source="salespersonRefundStatsData"
              :loading="refundDetailsLoading"
              :pagination="false"
              size="small"
            >
              <template #bodyCell="{ column, text, record }">
                <template v-if="column.key === 'refundAmount'">
                  <a-button
                    type="link"
                    @click="handleSalespersonClick(record.salespersonId)"
                    class="text-red-500"
                    :class="{
                      'font-bold':
                        selectedSalespersonId === record.salespersonId,
                    }"
                    style="height: auto; padding: 0"
                  >
                    ¥ {{ parseFloat(text || 0).toFixed(2) }}
                  </a-button>
                </template>
                <template v-else-if="column.key === 'returnedTotal'">
                  <span
                    class="text-red-500"
                    :class="{
                      'font-bold':
                        selectedSalespersonId === record.salespersonId,
                    }"
                  >
                    {{ text }}
                  </span>
                </template>
              </template>
            </a-table>
          </template>

          <!-- 新增：退货退款明细表格 -->
          <a-divider>退货退款明细</a-divider>
          <!-- **新增：总计数量显示** -->
          <div class="mb-2 flex justify-end">
            <span class="mr-4 font-bold text-red-500">总退款金额：¥ {{ totalRefundAmountDisplay }}</span>
            <span class="font-bold text-red-500">总退货数量：{{ totalReturnNumDisplay }} 件</span>
          </div>
          <a-table
            :columns="refundDetailColumns"
            :data-source="refundDetailsData"
            :loading="refundDetailsLoading"
            :pagination="{
              current: refundDetailsCurrentPage,
              pageSize: refundDetailsPageSize,
              total: refundDetailsTotal,
              showSizeChanger: true,
              showQuickJumper: true,
            }"
            @change="onRefundDetailsTableChange"
            size="small"
          >
            <!-- **新增：自定义渲染退款金额，确保显示为红色** -->
            <template #bodyCell="{ column, text }">
              <template v-if="column.key === 'refundAmount'">
                <span class="text-red-500">{{ text }}</span>
              </template>
              <template v-else-if="column.key === 'returnNum'">
                <span class="text-red-500">{{ text }}</span>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>

    <!-- 注册详情弹窗 -->
    <PaymentDetailModal
      v-model:visible="isDetailModalVisible"
      :title="detailModalTitle"
      :params="detailModalParams"
    />
  </div>
</template>

<style scoped>
/* 原有的样式保持不变 */
.p-4 {
  padding: 16px;
}

.flex {
  display: flex;
}

.flex-1 {
  flex: 1;
}

.flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
}

.flex-between {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
}

.h-120 {
  height: 120px;
}

.wd-33 {
  width: 33.33%;
}

.wd-66 {
  width: 66.66%;
}

.text-28-main-700 {
  font-size: 28px;
  font-weight: 700;
  color: #333;
}

.text-14-sub-400 {
  font-size: 14px;
  font-weight: 400;
  color: #666;
}

.text-14-tip-500 {
  font-size: 14px;
  font-weight: 500;
  color: #999;
}

.text-18-sub-600 {
  font-size: 18px;
  font-weight: 600;
  color: #666;
}

.text-16-tip {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.line-blue {
  width: 3px;
  height: 18px;
  margin-top: 4px;
  background: linear-gradient(336deg, #7383fa 3%, #2365ec 93%);
  border-radius: 10px;
  opacity: 1;
}

.ml-2 {
  margin-left: 8px;
}

.ml-4 {
  margin-left: 16px;
}

.ml-8 {
  margin-left: 32px;
}

.mt-4 {
  margin-top: 16px;
}

.mt-8 {
  margin-top: 32px;
}

.card {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  width: calc(25% - 12px);
  min-height: 600px;
  max-height: 600px;
  overflow-y: auto;
  background: linear-gradient(
    180deg,
    rgb(241 235 255 / 50%) 0%,
    rgb(230 237 253 / 0%) 100%
  );
  border: 1px solid #e1e6f1;
  border-radius: 8px;
  opacity: 1;
}

.card .ant-table-wrapper {
  flex-grow: 1;
}

.flex-end {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

/* 为卡片内的筛选控件添加新样式 */
.filter-controls {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-top: 10px;
  margin-bottom: 10px;
}

.filter-controls-vertical {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-top: 10px;
  margin-bottom: 10px;
}
</style>
